<template>
  <div class="add-bill-container">
    <h4>新增账单</h4>
    <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="120px"
        class="demo-ruleForm"
    >
      <!-- 账单编码 -->
      <el-form-item label="账单编码" prop="billCode">
        <el-input
            v-model="addForm.billCode"
            placeholder="请输入唯一账单编码"
            clearable
        ></el-input>
      </el-form-item>

      <!-- 商品信息 -->
      <el-form-item label="商品名称" prop="productName">
        <el-input
            v-model="addForm.productName"
            placeholder="请输入商品名称"
            clearable
        ></el-input>
      </el-form-item>

      <el-form-item label="商品描述" prop="productDesc">
        <el-input
            type="textarea"
            v-model="addForm.productDesc"
            :rows="3"
            placeholder="请输入商品描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="商品数量" prop="productCount">
        <el-input
            v-model.number="addForm.productCount"
            type="number"
            placeholder="请输入商品数量"
            :min="1"
        ></el-input>
      </el-form-item>

      <el-form-item label="商品单位" prop="productUnit">
        <el-select
            v-model="addForm.productUnit"
            placeholder="请选择单位"
            clearable
            style="width: 100%"
        >
          <el-option
              v-for="item in productUnitList"
              :key="item"
              :label="item"
              :value="item"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品总额" prop="totalPrice">
        <el-input
            v-model.number="addForm.totalPrice"
            type="number"
            placeholder="请输入商品总额"
            :min="0"
        >
          <template #prefix>¥</template>
        </el-input>
      </el-form-item>

      <!-- 支付状态 -->
      <el-form-item label="是否支付" prop="isPayment">
        <el-radio-group v-model="addForm.isPayment">
          <el-radio label="1">未支付</el-radio>
          <el-radio label="2">已支付</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 供应商选择 -->
      <el-form-item label="供应商" prop="providerId">
        <el-select
            v-model="addForm.providerId"
            placeholder="请选择供应商"
            filterable
            clearable
            :loading="loadingProviders"
            @focus="fetchProviders"
            style="width: 100%"
        >
          <el-option
              v-for="item in providerList"
              :key="item.id"
              :label="item.proName"
              :value="item.id"
          />
          <!-- 统一加载和空状态提示 -->
          <template v-if="loadingProviders">
            <el-option disabled label="加载中..."></el-option>
          </template>
          <template v-else-if="providerList.length === 0">
            <el-option disabled label="暂无供应商数据"></el-option>
          </template>
        </el-select>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button
            type="primary"
            @click="submitForm('addForm')"
            :loading="submitting"
        >
          {{ submitting ? '提交中...' : '保存' }}
        </el-button>
        <el-button @click="resetForm('addForm')">清空</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessage } from "element-plus";
import {addBill, checkBillCode} from "@/api/bill";
import request from '@/utils/request';

export default {
  name: 'AddBill',
  data() {

    const validateNumber = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        return callback(new Error('请输入数值'));
      }
      if (isNaN(value)) {
        return callback(new Error('必须为数字值'));
      }
      if (value < 0) {
        return callback(new Error('必须大于等于0'));
      }
      callback();
    };

    const validateBillCode = async (rule, value, callback) => {
      if (!value || value.trim().length < 3) {
        return callback(new Error('请输入至少3位账单编码'));
      }

      try {
        const res = await checkBillCode(value);
        if (res.data === true) {
          // 编码已存在
          this.$message.error('该账单编码已存在，请修改');
          callback(new Error(' ')); // 空错误信息，只显示上面的提示
        } else {
          callback(); // 验证通过
        }
      } catch (error) {
        console.error('验证失败:', error);
        this.$message.error('验证账单编码失败');
        callback(new Error('验证失败'));
      }
    };

    return {
      addForm: {
        billCode: '',
        productName: '',
        productDesc: '',
        productCount: null,
        productUnit: '',
        totalPrice: null,
        isPayment: '1',
        providerId: null
      },
      productUnitList: ['瓶', '块', '斤', '袋', '个'],
      providerList: [],

      loadingProviders: false,
      submitting: false,
      rules: {
        billCode: [
          { required: true, message: '请输入账单编码', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在3到30个字符', trigger: 'blur' },
          { validator: validateBillCode, trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        productCount: [
          { required: true, validator: validateNumber, trigger: 'blur' }
        ],
        productUnit: [
          { required: true, message: '请选择商品单位', trigger: 'change' }
        ],
        totalPrice: [
          { required: true, validator: validateNumber, trigger: 'blur' }
        ],
        providerId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ]
      }
    };
  },
  mounted() {
    this.fetchProviders();
  },
  methods: {
    
    async fetchProviders() {
      if (this.providerList.length > 0) return;

      this.loadingProviders = true;
      try {
        const res = await request({
          url: '/provider/list',
          method: 'get'
        });
        
        const responseData = res.data;
        console.log("供应商接口完整响应:", responseData);
        
        if (responseData.flag === true) {
          // 假设 responseData.data.list 是供应商数组
          this.providerList = responseData.data.list || [];
          console.log('供应商原始数组:', this.providerList);
          console.log("账单页面下拉供应商:", this.providerList);
        } else {
          ElMessage.error(responseData.message || '获取供应商列表失败');
          this.providerList = [];
        }
      } catch (error) {
        console.error("获取供应商列表出错:", error);
        ElMessage.error('网络请求失败');
        this.providerList = [];
      } finally {
        this.loadingProviders = false;
      }
    },

    async submitForm(formName) {
      try {
        // 1. 验证表单
        await this.$refs[formName].validate();

        // 2. 检查账单编码
        const codeCheck = await checkBillCode(this.addForm.billCode);
        if (!codeCheck.data) {
          this.$message.error('该账单编码已被使用，请修改');
          return;
        }

        // 3. 准备提交数据 - 处理供应商字段
        const submitData = { ...this.addForm };
        
        // 将providerId转换为proName，因为后端期望的是proName字段
        if (submitData.providerId) {
          const selectedProvider = this.providerList.find(p => p.id === submitData.providerId);
          if (selectedProvider) {
            submitData.proName = selectedProvider.proName;
          }
          // 移除providerId字段，因为后端不需要
          delete submitData.providerId;
        }

        // 4. 提交数据
        this.submitting = true;
        const response = await addBill(submitData);

        // 5. 响应处理 - 关键修改部分
        if (response.flag === true) {  // 明确检查flag字段
          this.$message.success(response.message || '账单添加成功');
          this.resetForm(formName);
          this.$router.push('/homepage/billList'); // 修改跳转路径
        } else {
          this.$message.error(response.message || '添加失败');
        }
      } catch (error) {
        // 6. 错误处理
        console.error('提交错误:', error);
        const errorMsg = error.response?.data?.message
            || error.message
            || '提交失败，请检查网络连接';
        this.$message.error(errorMsg);
      } finally {
        this.submitting = false;
      }
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.addForm.isPayment = '1';
    },

    goBack() {
      this.$router.go(-1);
    }
  }
}
</script>

<style scoped>
.add-bill-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.demo-ruleForm {
  background: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 22px;
}

.el-textarea {
  min-height: 100px;
}

</style>